package com.alai04.android.scoreboard;

import android.content.Context;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import com.alai04.android.preference.SeekBarPreference;
import com.alai04.android.preference.AutoCompletePreference;

public class Prefs extends PreferenceActivity {
	// Option names and default values
	private static final String OPT_NAME_PREFIX = "name";
	private static String OPT_PN = "";
	private static String OPT_BID = "";
	public static final int MAX_BID_TIMES = 4;
	private PlayerNames names;

	private SeekBarPreference bidPref;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);

		OPT_PN = getString(R.string.prefkey_players);
		OPT_BID = getString(R.string.prefkey_bidtimes);
		SeekBarPreference sbPref = (SeekBarPreference) findPreference(OPT_PN);
		sbPref.setLimit(3, 4);
		sbPref.setInterval(1);
		bidPref = (SeekBarPreference) findPreference(OPT_BID);
		bidPref.setLimit(1, getPN(this));
		bidPref.setInterval(1);

		names = new PlayerNames(this);
		Preference prefName;
		Preference.OnPreferenceChangeListener onPrefChg = new Preference.OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				preference.setSummary(newValue.toString());
				names.add(newValue.toString());
				return true;
			}
		};
		for (int i = 1; i <= 4; i++) {
			prefName = (Preference) findPreference(OPT_NAME_PREFIX + i);
			prefName.setSummary(getName(getApplicationContext(), i));
			prefName.setOnPreferenceChangeListener(onPrefChg);
			AutoCompleteTextView actv = (AutoCompleteTextView) ((AutoCompletePreference) prefName)
					.getEditText();
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					R.layout.list_item, names.toArray());
			actv.setAdapter(adapter);
			actv.setSingleLine();
		}

		Preference.OnPreferenceChangeListener onPNChg = new Preference.OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				bidPref.setLimit(1, Integer.valueOf(newValue.toString()));
				return true;
			}
		};
		sbPref.setOnPreferenceChangeListener(onPNChg);
	}

	public static int getPN(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context).getInt(
				OPT_PN, 3);
	}

	public static int getBID(Context context) {
		return PreferenceManager.getDefaultSharedPreferences(context).getInt(
				OPT_BID, 1);
	}

	public static String getName(Context context, int n) {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(OPT_NAME_PREFIX + n,
						context.getString(R.string.name_default));
	}
}